package com.zz.utils;

import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvRow;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.zz.common.ZohoRecord;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class BulkUtil {

    @Value("${zoho.apiBulkUrl}")
    private String apiBulkUrl;

    @Value("${zoho.zipFileDest}")
    private String zipFileDest;

    @Autowired
    ZohoRecord zohoRecord;


    //创建bulk任务
    public JSONObject postEntries(String query) {
        String settleAccountResult = HttpRequest.post(apiBulkUrl)
                .body(query, "application/json")
                .header(Header.AUTHORIZATION, "Zoho-oauthtoken " + zohoRecord.getAccessToken())
                .timeout(20000)
                .execute().body();
        if (StrUtil.isNotBlank(settleAccountResult)) {
            JSONObject tmpObj = JSONObject.parseObject(settleAccountResult);
            return tmpObj;
        } else {
            return new JSONObject();
        }
    }

    // bulk
    public List<CsvRow> getBulkCSVData(String token, String query, List<CsvRow> result) {
        log.info("query:{}", query);
        //创建批量读取任务
        String jobId = createBulkJob(token, query);
        if (StringUtils.isNotBlank(jobId)) {
            // 获取批量读取任务明细
            log.info("Get the Status of the Bulk Read Job");
            boolean boo = GetStatusBulkJob(token, jobId);

            // 下载批量读取结果
            List<CsvRow> csvRows = downBulkResult(token, zipFileDest, jobId);
            if (Objects.nonNull(csvRows)) {
                result.addAll(csvRows);
            }

            if (boo) {
                JSONObject queryJson = JSONObject.parseObject(query);
                JSONObject tempQuery = queryJson.getJSONObject("query");
                if(Objects.nonNull(tempQuery)){
                    if(Objects.nonNull(tempQuery.getInteger("page"))){
                        tempQuery.put("page", tempQuery.getInteger("page") + 1);
                        queryJson.put("query", tempQuery);
                        getBulkCSVData(token, queryJson.toJSONString(), result);
                    }

                }



            }

        }
        return result;
    }


    public static String createBulkJob(String token, String query) {
        log.info("Create Bulk Read job");
        String url = "https://www.zohoapis.com.cn/crm/bulk/v7/read";
        JSONObject createData = HttpUtil.postDataByHead(token, url, query);
        if (Objects.nonNull(createData) && Objects.nonNull(createData.getJSONArray("data")) && createData.getJSONArray("data").size() > 0) {
            JSONObject json = createData.getJSONArray("data").getJSONObject(0);
            if ("success".equals(json.getString("status"))) {
                return json.getJSONObject("details").getString("id");
            }
        }
        log.info("Create Bulk Read job error = " + createData.toJSONString());
        return "";
    }

    public static boolean GetStatusBulkJob(String token, String jobId) {

        String url = "https://www.zohoapis.com.cn/crm/bulk/v7/read/" + jobId;
        HashMap<String, String> map = new HashMap<>();
        map.put("Authorization", "Zoho-oauthtoken " + token);

        boolean moreRecords;

        while (true) {
            JSONObject data = HttpUtil.getData(url, map);
            if (Objects.nonNull(data) && Objects.nonNull(data.getJSONArray("data")) && data.getJSONArray("data").size() > 0) {
                JSONObject jsonData = data.getJSONArray("data").getJSONObject(0);
                String state = jsonData.getString("state");
                System.out.println("state = " + state);
                if ("COMPLETED".equals(state)) {
                    moreRecords = jsonData.getJSONObject("result").getBoolean("more_records");
                    break;
                }
                ThreadUtil.safeSleep(10000);

            } else {
                log.info("Get the Status of the Bulk Read Job error = " + data.toJSONString());
                return false;
            }
        }
        return moreRecords;
    }

    public List<CsvRow> downBulkResult(String token, String destFile, String jobId) {
        log.info("Download Bulk Read Result");
        File zipFile = new File(destFile + jobId + ".zip");
        HttpRequest.get("https://www.zohoapis.com.cn/crm/bulk/v7/read/" + jobId + "/result")
                .header(Header.AUTHORIZATION, "Zoho-oauthtoken " + token)
                .executeAsync().writeBody(zipFile);

        if (zipFile.exists()) {
            ZipUtil.unzip(zipFile);
            CsvReader reader = CsvUtil.getReader();
            CsvData read = reader.read(new File(destFile + jobId + "/" + jobId + ".csv"));
            System.out.println("本次共计：" + read.getRowCount() + "条数据");
            return read.getRows();
        }
        return null;
    }


}
